﻿using System;
using System.Linq;
using System.Text;
using CodeStash.Common.Encryption;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Collections.Specialized;
using System.Collections.Generic;

namespace CodeStash.Addin.Core
{
    public static class Utilities
    {
        public static string GetStringForWebsiteCall(this string value)
        {
            if (string.IsNullOrWhiteSpace(value))
                return string.Empty;

            if (EncryptionHelper.EncryptionEnabled)
                return EncryptionHelper.GetEncryptedValue(value);
            return value;
        }

        internal static T GetValue<T>(Byte[] results) where T : class
        {
            using (MemoryStream ms = new MemoryStream(results))
            {
                DataContractJsonSerializer jss = new DataContractJsonSerializer(typeof(T));
                return (T)jss.ReadObject(ms);
            }
        }


        internal static void AddValue(NameValueCollection values, string key, object value)
        {
            DataContractJsonSerializer jss = new DataContractJsonSerializer(value.GetType());
            using (MemoryStream ms = new MemoryStream())
            {
                jss.WriteObject(ms, value);
                string json = Encoding.UTF8.GetString(ms.ToArray());
                values.Add(key, json);
            }
        }
    }
}
